package com.gongpingjialoan.activity.category;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.DataManager;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.CityData;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.ModifyMileBoardCast;
import com.gongpingjialoan.view.DatePickerDialog;
import com.gongpingjialoan.widget.LoadingDialog;

import org.json.JSONObject;

/**
 * Created by Administrator on 2015/10/28.
 */
public class ChooseLikeCarActivity extends BaseActivity implements View.OnClickListener, NetDataJson.OnNetDataJsonListener {

    private Button mBtnSure;

    private TextView mTxtBrand, mTxtDate, cityT;

    private EditText mEdtMile;

    private CityData mCityData;

    private String mModelThumbnail, mMile, maxyear, minyear, mBrandSlug, mBrandName, mModelSlug, mModelName, mModelDetailSlug, mModelDetailName;

    private DatePickerDialog dateDialog;

    private final int REQUEST_CITY_FRAGMENT = 1;

    private final int REQUEST_BRAND = 2;

    private String mYear;

    private String mMonth;

    private LoadingDialog loadingDialog;

    private NetDataJson netWork;

    private boolean isdefalut = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_like_car);
        loadingDialog = new LoadingDialog(this);
        isdefalut = getIntent().getBooleanExtra("isdefalut", true);
        mCityData = GPJApplication.getInstance().getCityData();
        setTitle("选择爱车");
        initView();
    }

    private void initView() {
        netWork = new NetDataJson(this);
        mBtnSure = (Button) findViewById(R.id.button);
        mTxtBrand = (TextView) findViewById(R.id.txt_model);
        mTxtDate = (TextView) findViewById(R.id.txt_year);
        mEdtMile = (EditText) findViewById(R.id.editText);
        cityT = (TextView) findViewById(R.id.txt_city);
        SharedPreferences sharedPreferences = getSharedPreferences("user_city", Context.MODE_PRIVATE);
        String user_city = sharedPreferences.getString("city", "");
        if (TextUtils.isEmpty(user_city)) {
            cityT.setText(mCityData.mCurrentCity);
        } else {
            cityT.setText(user_city);
        }

        cityT.setOnClickListener(this);
        mBtnSure.setOnClickListener(this);
        mTxtBrand.setOnClickListener(this);
        mTxtDate.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        if (v == cityT) {
            Intent intent = new Intent();
            intent.putExtra("needProvince", false);
            intent.setClass(this, CityActivity.class);
            startActivityForResult(intent, REQUEST_CITY_FRAGMENT);
        } else if (v == mTxtBrand) {
            if (!DataManager.getInstance().getLoadingDataSuccess()) {
                Toast.makeText(this, "数据未加载成功,请检查网络是否连接!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent();
            intent.setClass(this, CategoryActivity.class);
            intent.putExtra(Const.BRAND_NAME_KEY, mBrandName);
            intent.putExtra(Const.BRAND_SLUG_KEY, mBrandSlug);
            intent.putExtra(Const.MODEL_NAME_KEY, mModelName);
            intent.putExtra(Const.MODEL_SLUG_KEY, mModelSlug);
            intent.putExtra(Const.MODEL_DETAIL_NAME_KEY, mModelDetailName);
            intent.putExtra(Const.MODEL_DETAIL_SLUG_KEY, mModelDetailSlug);

            intent.putExtra("needModelDetailFragment", true);
            startActivityForResult(intent, REQUEST_BRAND);
        } else if (v == mTxtDate) {
            if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                    || mTxtBrand.getText().toString().equals("请选择")) {
                Toast.makeText(this, "请选择车辆型号!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (null != dateDialog && maxyear != null) {
                dateDialog.show();
            } else {
                Toast.makeText(this, "上牌时间数据加载中!",
                        Toast.LENGTH_SHORT).show();
            }
        } else if (v == mBtnSure) {
            if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                    || mTxtBrand.getText().toString().equals("请选择")) {
                Toast.makeText(this, "请选择车辆型号!",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(mTxtDate.getText().toString())||"请选择".equals(mTxtDate.getText().toString())) {
                Toast.makeText(this, "请选择上牌时间!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            mMile = mEdtMile.getText().toString();
            Double mile = -1.0;
            if (TextUtils.isEmpty(mMile)) {
                Toast.makeText(this, "请输入行驶里程!",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (mMile.length() > 5) {
                Toast.makeText(this,
                        "请输入正确的公里数，小数和整数均不能超过2位数!", Toast.LENGTH_SHORT)
                        .show();
                return;
            }
            try {
                mile = Double.valueOf(mMile);
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请填写正确的行驶里程（0-100万公里）",
                        Toast.LENGTH_SHORT).show();
                return;

            }
            if (mile < 0 || mile > 100) {
                Toast.makeText(this, "请填写正确的行驶里程（0-100万公里）",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            loadingDialog.show();
            mMile = mile + "";
            netWork.setUrl(API.add_like_car);
            netWork.addParam("brand", mBrandSlug);
            netWork.addParam("model", mModelSlug);
            netWork.addParam("model_detail", mModelDetailSlug);
            netWork.addParam("city", cityT.getText().toString());
            netWork.addParam("year", mYear);
            netWork.addParam("month", mMonth);
            netWork.addParam("mile", mMile);
            netWork.addParam("is_default", isdefalut);

            netWork.request("post");
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String city = b.getString("city");
                    if (city != null) {
                        cityT.setText(city);
                    }
                    break;
                // 车型选择回调
                case REQUEST_BRAND:
                    Bundle bundle = data.getExtras();
                    onBrandSelceted(bundle);
                    break;

                default:
                    break;
            }
        }

    }


    // 选择完车型后,调用这辆
    public void onBrandSelceted(Bundle bundle) {
        maxyear = null;
        minyear = null;
        mBrandSlug = bundle.getString("brandSlug");
        mBrandName = bundle.getString("brandName");
        mModelSlug = bundle.getString("modelSlug");
        mModelName = bundle.getString("modelName");
        mModelDetailName = bundle.getString("modelDetailName");
        mModelDetailSlug = bundle.getString("modelDetailSlug");
        mModelThumbnail = bundle.getString("modelThumbnail");

        // 查询二手车,选择车型后,车辆型号TextView的展示
        if (mModelDetailName == null) {
            mTxtBrand.setText(mModelName);
        } else {
            mTxtBrand.setText(mModelName + " " + mModelDetailName);
        }

        mTxtBrand.setTextColor(Color.parseColor("#666666"));

        // delete the date data if it is not null
        mTxtDate.setText("请选择");
        mTxtDate.setTextColor(Color.parseColor("#18A0E0"));

        // 上牌年份选择弹框
        dateDialog = new DatePickerDialog(this);
        dateDialog.setMinMonth(1);
        dateDialog.setMaxMonth(12);

        dateDialog.setDialogCallBack(new DatePickerDialog.OnDialogCallBack() {

            @Override
            public void onSelectResult(String year, String month, String day) {
                mYear = year;
                mMonth = month;
                if (TextUtils.isEmpty(month)) {
                    mTxtDate.setText(year + "年");
                } else {
                    mTxtDate.setText(year + "年" + month + "月");
                }
                mTxtDate.setTextColor(Color.parseColor("#666666"));
            }


        });

        // // 如果是评估我的车,上牌年份的日期从返回的数据bundle中取
        // if (radioG.getCheckedRadioButtonId() == R.id.radio_left)
        // {
        maxyear = bundle.getString("maxyear");
        minyear = bundle.getString("minyear");

        dateDialog.setMonthPickerVisibility(View.VISIBLE);
        dateDialog.setMinYear(Integer.parseInt(minyear));
        dateDialog.setMaxYear(Integer.parseInt(maxyear));
        if (maxyear == null) {
            Toast.makeText(this, "没有可选的上牌时间!", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mEdtMile.setText("");

        if (TextUtils.isEmpty(mTxtBrand.getText().toString())
                || mTxtBrand.getText().toString().equals("请选择")) {
            Toast.makeText(this, "请选择车辆型号!",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (null != dateDialog && maxyear != null) {
            dateDialog.show();
        } else {
            Toast.makeText(this, "上牌时间数据加载中!",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        loadingDialog.dismiss();
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (isdefalut) {
            if (MainActivity.main != null)
                MainActivity.main.mUserHomeFragment.refresh();
            Intent intent = new Intent(ModifyMileBoardCast.MODIFY_MILE_ACTION);
            intent.putExtra("action" , "manager");
            sendBroadcast(intent);
        }
        loadingDialog.dismiss();
        setResult(RESULT_OK);
        finish();
    }
}
